package com.future.controller;

import javax.validation.constraints.NotNull;

import com.future.common.annotation.ControllerMapping;
import com.future.common.annotation.NoNeedLogin;
import com.future.common.base.BaseController;
import com.future.common.global.GlobalPara;
import com.future.common.global.PlatFormContext;
import com.future.dao.ParentDao;
import com.future.dao.SysUserDao;
import com.future.dao.TeacherDao;
import com.future.model.SysUser;
import com.future.model.Teacher;
import com.future.requestbean.Parent;
import com.future.requestbean.ParentUpdate;
import com.future.service.SysUserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.tx.Tx;

@ControllerMapping("/parent")
public class ParentController extends BaseController {
	@Inject
	private ParentDao parentDao;
	@Inject
	private SysUserService sysUserService;
	@Inject
	private SysUserDao sysDao;
	@Inject
	private TeacherDao teacherDao;

	@NoNeedLogin
	@Before(Tx.class)
	public void addParent() {
		Parent parent = getJsonBody(Parent.class);
		this.sysUserService.checkUserNameExisted(parent.getLoginUsername());
		com.future.model.Parent pM = beanToModel(parent, com.future.model.Parent.class);
		pM.save();
		Long parentId = pM.getParentid();
		this.sysUserService.saveUser(parent.getLoginUsername(), GlobalPara.PARENT_TYPE, parentId);

		renderSuccess();
	}

	@Before(Tx.class)
	public void deleteParent(@NotNull(message = "删除家长的信息为空") Long parentid) {
		this.parentDao.deleteById(parentid);
		SysUser sysUser = this.sysDao.getSysUserByUserTypeAndUserInfoId(parentid, GlobalPara.PARENT_TYPE);
		this.sysDao.deleteById(sysUser.getUserid());
		renderSuccess();
	}

	public void getParents() {
		String userType = PlatFormContext.getCurrentUser().getUserType();
		Long bjid = null;
		if (GlobalPara.MANAGER_TYPE.equals(userType)) {
			bjid = null;
		}
		if (GlobalPara.TEACHER_TYPE.equals(userType)) {
			Teacher teacher = this.teacherDao.findById(getCurrentUser().getUserinfoid());
			bjid = teacher.getBjid();
		}
		renderResult("parents", this.parentDao.getParents(bjid));
	}

	@Before(Tx.class)
	public void updateParent() {
		com.future.model.Parent parent = getJsonBodyToModel(ParentUpdate.class, com.future.model.Parent.class);
		this.parentDao.update(parent);
		renderSuccess();
	}

	/**
	 * 获取app登录用户的信息
	 */
	public void getParentInfo() {
		renderResult("userinfo", this.parentDao.getParentInfo(getCurrentUserId()));
	}

	/**
	 * 修改头像
	 */
	@Before(Tx.class)
	public void updateImage(String imgurl) {
		SysUser user = this.sysDao.findById(getCurrentUserId());
		Long userinfoId = user.getUserinfoid();
		this.parentDao.findById(userinfoId).setParentimg(imgurl).update();
		renderSuccess();
	}

}
